package com.github.willisaway.core.util;

import java.util.ArrayList;
import java.util.List;

import com.github.willisaway.core.inter.TreeNode;

public class TreeUtil {
    /**
     * 两层循环实现建树
     * 
     * @param treeNodes
     * 传入的树节点列表
     * @return
     */
    public static <N extends TreeNode> List<N> build(List<N> treeNodes, Object root) {
        List<N> trees = new ArrayList<N>();
        for (N treeNode : treeNodes) {
            if (treeNode.idEquals(root, treeNode.getParentNodeId())) {
                trees.add(treeNode);
            }
            for (N it : treeNodes) {
                if (treeNode.idEquals(it.getParentNodeId(), treeNode.getNodeId()) ) {
                    if (treeNode.getNodeChilds() == null) {
                        treeNode.setNodeChilds(new ArrayList<TreeNode>());
                    }
                    treeNode.getNodeChilds().add(it);
                }
            }
        }
        return trees;
    }

    /**
     * 使用递归方法建树
     * 
     * @param treeNodes
     * @return
     */
    public static <N extends TreeNode> List<N> buildByRecursive(List<N> treeNodes, Object root) {
        List<N> trees = new ArrayList<N>();
        for (N treeNode : treeNodes) {
            if (treeNode.idEquals(root, treeNode.getParentNodeId())) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     * 
     * @param treeNodes
     * @return
     */
    public static <N extends TreeNode> N findChildren(N treeNode, List<N> treeNodes) {
        for (N it : treeNodes) {
            if (treeNode.idEquals(treeNode.getNodeId(), it.getParentNodeId()) ) {
                if (treeNode.getNodeChilds() == null) {
                    treeNode.setNodeChilds(new ArrayList<TreeNode>());
                }
                treeNode.getNodeChilds().add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }
}
